<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>登录</span>
        </div>
      </template>
      <!-- 网页的作用1是展示数据，2是收集数据，收集数据靠表单 -->
       <!--  -->
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username" >
          <el-input  v-model="loginForm.username" ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button  type="primary" @click="submitForm">登录</el-button>
          <el-button type="warning"  @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    

    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import axios from '@/utils/request.js';
import { useRouter } from 'vue-router';
const router = useRouter();

    //ref方法是定义一个变量，并且初始化赋值，同时让这个变量可以在模板中使用，这种变量是响应式变量
    const loginFormRef = ref(null);
    //reactive定义响应式对象
    const loginForm = reactive({
      username: '',
      password: '',
    });
    //定义表单验证规则对象
    const rules = reactive({
      //对username字段进行不为空验证，message是提示信息，trigger是验证时机,blur光标离开时
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' },],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' },],
    });

    //定一个方法submitForm
    const submitForm = () => {
      loginFormRef.value.validate((valid) => {
        if (valid) {
           //发送登录请求
          axios(
            {
              url: '/login.do',
              method: 'post',
              params: {
                name: loginForm.username,
                pass: loginForm.password,
              },
            }).then((res) => {
                //res必须是json格式的才能识别
                if(res.result=='success'){
                  var id=res.userinfo.id;
                  var username=res.userinfo.name;
                  router.push({
                    path: '/main',
                    query: { userid: id,username:username },
                  });
                    //window.location.href = '/main';
                }else {
                    ElMessage.error('请输入正确的用户名和密码!');
                    return false;
            }
            })
            

          //导向主界面
            // 
        
        } else {
          ElMessage.error('请输入正确的用户名和密码!');
          return false;
        }
      });
    };
    //定一个方法resetForm，重置表单
    const resetForm = () => {
      loginFormRef.value.resetFields();
    };
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vW;
  background-color: #f0f2f5;
}
.box-card {
  width: 400px;
}
</style>